import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import apiService from '../services/api.js'
import { useDataStore } from './useDataStore.js'

/**
 * 文件上传管理Hook
 * 处理图标上传、文件上传等相关功能
 */
export function useFileUpload() {
  const dataStore = useDataStore()
  
  // 上传状态
  const uploading = ref(false)
  const uploadProgress = ref(0)
  
  // 图标上传相关
  const iconUploadRef = ref(null)
  const iconPreviewUrl = ref('')
  
  /**
   * 处理图标文件选择
   * @param {File} file - 选择的文件
   * @param {Object} form - 表单对象
   */
  const handleIconFileSelect = (file, form) => {
    if (!file) return
    
    // 验证文件类型
    const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/svg+xml']
    if (!allowedTypes.includes(file.type)) {
      ElMessage.error('请选择有效的图片文件（JPG、PNG、GIF、SVG）')
      return false
    }
    
    // 验证文件大小（限制为2MB）
    const maxSize = 2 * 1024 * 1024
    if (file.size > maxSize) {
      ElMessage.error('文件大小不能超过2MB')
      return false
    }
    
    // 设置表单的图标文件
    if (form) {
      form.iconFile = file
    }
    
    // 创建预览URL
    const reader = new FileReader()
    reader.onload = (e) => {
      iconPreviewUrl.value = e.target.result
    }
    reader.readAsDataURL(file)
    
    return true
  }
  
  /**
   * 清除图标预览
   * @param {Object} form - 表单对象
   */
  const clearIconPreview = (form) => {
    iconPreviewUrl.value = ''
    if (form) {
      form.iconFile = null
      form.icon = ''
    }
  }
  
  /**
   * 带文件上传的项目保存方法
   * @param {Object} formData - 表单数据
   * @param {File} iconFile - 图标文件
   * @param {boolean} isEdit - 是否为编辑模式
   */
  const saveItemWithFile = async (formData, iconFile, isEdit = false) => {
    const form = new FormData()
    
    // 字段名映射：前端字段名 -> 后端字段名
    const fieldMapping = {
      'title': 'name',
      'url': 'external_url',
      // 其他字段保持原名
    }
    
    // 添加表单字段
    Object.keys(formData).forEach(key => {
      if (formData[key] !== null && formData[key] !== undefined) {
        const backendFieldName = fieldMapping[key] || key
        form.append(backendFieldName, formData[key])
      }
    })
    
    // 添加图标文件
    if (iconFile) {
      form.append('icon', iconFile)
    }
    
    try {
      uploading.value = true
      let result
      
      if (isEdit && formData.id) {
        // 更新现有项目
        result = await apiService.items.updateWithFile(formData.id, form)
      } else {
        // 创建新项目
        result = await apiService.items.createWithFile(form)
      }
      
      // 刷新相关数据以确保界面实时更新
      await Promise.allSettled([
        dataStore.fetchItems(),
        dataStore.fetchHierarchyData(),
        dataStore.fetchAvailableItems()
      ])
      
      ElMessage.success(isEdit ? '项目更新成功' : '项目创建成功')
      return result
      
    } catch (error) {
      console.error('保存项目失败:', error)
      ElMessage.error('保存项目失败，请重试')
      throw error
    } finally {
      uploading.value = false
      uploadProgress.value = 0
    }
  }
  
  /**
   * 上传单个文件
   * @param {File} file - 要上传的文件
   * @param {string} uploadType - 上传类型（如 'image', 'document' 等）
   */
  const uploadSingleFile = async (file, uploadType = 'image') => {
    if (!file) {
      ElMessage.error('请选择要上传的文件')
      return null
    }
    
    const formData = new FormData()
    formData.append('file', file)
    formData.append('type', uploadType)
    
    try {
      uploading.value = true
      const response = await apiService.upload.single(formData, {
        onUploadProgress: (progressEvent) => {
          uploadProgress.value = Math.round(
            (progressEvent.loaded * 100) / progressEvent.total
          )
        }
      })
      
      ElMessage.success('文件上传成功')
      return response.data
      
    } catch (error) {
      console.error('文件上传失败:', error)
      ElMessage.error('文件上传失败，请重试')
      throw error
    } finally {
      uploading.value = false
      uploadProgress.value = 0
    }
  }
  
  /**
   * 批量上传文件
   * @param {FileList} files - 要上传的文件列表
   * @param {string} uploadType - 上传类型
   */
  const uploadMultipleFiles = async (files, uploadType = 'image') => {
    if (!files || files.length === 0) {
      ElMessage.error('请选择要上传的文件')
      return []
    }
    
    const results = []
    uploading.value = true
    
    try {
      for (let i = 0; i < files.length; i++) {
        const file = files[i]
        uploadProgress.value = Math.round((i / files.length) * 100)
        
        const result = await uploadSingleFile(file, uploadType)
        if (result) {
          results.push(result)
        }
      }
      
      ElMessage.success(`成功上传 ${results.length} 个文件`)
      return results
      
    } catch (error) {
      console.error('批量上传失败:', error)
      ElMessage.error('批量上传失败，请重试')
      throw error
    } finally {
      uploading.value = false
      uploadProgress.value = 0
    }
  }
  
  /**
   * 重置上传状态
   */
  const resetUploadState = () => {
    uploading.value = false
    uploadProgress.value = 0
    iconPreviewUrl.value = ''
  }
  
  return {
    // 状态
    uploading,
    uploadProgress,
    iconUploadRef,
    iconPreviewUrl,
    
    // 方法
    handleIconFileSelect,
    clearIconPreview,
    saveItemWithFile,
    uploadSingleFile,
    uploadMultipleFiles,
    resetUploadState
  }
}